<template>
  <div class="course-management">
    <div class="page-header">
      <h1>课程管理</h1>
      <p>管理系统中的所有课程</p>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card">
      <el-form :model="searchForm" @submit.prevent="handleSearch" inline>
        <el-form-item label="课程名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入课程名称"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="课程代码">
          <el-input
            v-model="searchForm.code"
            placeholder="请输入课程代码"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="授课教师">
          <el-select v-model="searchForm.teacherId" placeholder="选择教师" clearable style="width: 150px">
            <el-option 
              v-for="teacher in teachers" 
              :key="teacher.id" 
              :label="teacher.name" 
              :value="teacher.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh">重置</el-button>
          <el-button type="success" @click="handleAdd" :icon="Plus">添加课程</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 课程列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>课程列表</span>
          <div>
            <el-tag>共 {{ total }} 门课程</el-tag>
          </div>
        </div>
      </template>

      <el-table :data="courses" v-loading="loading">
        <el-table-column prop="code" label="课程代码" width="120" />
        <el-table-column prop="name" label="课程名称" min-width="200" />
        <el-table-column prop="credit" label="学分" width="80" align="center" />
        <el-table-column prop="teacher_name" label="授课教师" width="120" />
        <el-table-column label="选课情况" width="150">
          <template #default="scope">
            <div class="enrollment-info">
              <span>{{ scope.row.current_enrollment || 0 }}/{{ scope.row.capacity }}</span>
              <el-progress 
                :percentage="getEnrollmentPercentage(scope.row)" 
                :stroke-width="4"
                :show-text="false"
                style="margin-top: 4px"
              />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="150">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="info" size="small" @click="handleViewStudents(scope.row)">
              学生
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 课程编辑对话框 -->
    <el-dialog v-model="editDialog.visible" :title="editDialog.title" width="600px">
      <el-form :model="editDialog.form" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="课程代码" prop="code">
          <el-input v-model="editDialog.form.code" :disabled="editDialog.mode === 'edit'" />
        </el-form-item>
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="editDialog.form.name" />
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input-number v-model="editDialog.form.credit" :min="1" :max="10" style="width: 100%" />
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input-number v-model="editDialog.form.capacity" :min="1" :max="500" style="width: 100%" />
        </el-form-item>
        <el-form-item label="授课教师" prop="teacher_id">
          <el-select v-model="editDialog.form.teacher_id" style="width: 100%">
            <el-option v-for="teacher in teachers" :key="teacher.id" :label="teacher.name" :value="teacher.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程描述">
          <el-input type="textarea" v-model="editDialog.form.description" :rows="3" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="editDialog.loading">
            {{ editDialog.mode === 'add' ? '创建' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 学生列表对话框 -->
    <el-dialog v-model="studentDialog.visible" :title="studentDialog.title" width="800px">
      <el-table :data="studentDialog.students" v-loading="studentDialog.loading">
        <el-table-column prop="student_id" label="学号" width="120" />
        <el-table-column prop="student_name" label="姓名" width="120" />
        <el-table-column prop="selection_date" label="选课时间" width="150">
          <template #default="scope">
            {{ formatDate(scope.row.selection_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="grade" label="成绩" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.grade" :type="getGradeType(scope.row.grade)" size="small">
              {{ scope.row.grade }}
            </el-tag>
            <span v-else class="no-grade">未录入</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { getAllCourses, createCourse, updateCourse, deleteCourse } from '@/api/course'
import { getAllUsers } from '@/api/user'
import { getCourseSelections } from '@/api/selection'

const loading = ref(false)
const courses = ref([])
const teachers = ref([])
const total = ref(0)
const editFormRef = ref(null)

const searchForm = reactive({
  name: '',
  code: '',
  teacherId: ''
})

const pagination = reactive({
  page: 1,
  limit: 20
})

const editDialog = reactive({
  visible: false,
  title: '',
  mode: 'add',
  loading: false,
  form: {
    code: '',
    name: '',
    credit: 2,
    capacity: 50,
    teacher_id: '',
    description: ''
  }
})

const studentDialog = reactive({
  visible: false,
  title: '',
  students: [],
  loading: false
})

const editRules = {
  code: [
    { required: true, message: '请输入课程代码', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入课程名称', trigger: 'blur' }
  ],
  credit: [
    { required: true, message: '请输入学分', trigger: 'blur' }
  ],
  capacity: [
    { required: true, message: '请输入容量', trigger: 'blur' }
  ],
  teacher_id: [
    { required: true, message: '请选择授课教师', trigger: 'change' }
  ]
}

// 计算选课进度百分比
const getEnrollmentPercentage = (course) => {
  if (!course.capacity || course.capacity === 0) return 0
  return Math.round((course.current_enrollment || 0) / course.capacity * 100)
}

// 获取成绩类型
const getGradeType = (grade) => {
  const score = parseFloat(grade)
  if (score >= 90) return 'success'
  if (score >= 80) return ''
  if (score >= 70) return 'warning'
  if (score >= 60) return 'info'
  return 'danger'
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'selected': return 'success'
    case 'completed': return 'info'
    case 'dropped': return 'danger'
    default: return ''
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'selected': return '在读'
    case 'completed': return '已完成'
    case 'dropped': return '已退课'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 获取教师列表
const fetchTeachers = async () => {
  try {
    const response = await getAllUsers({ role: 'teacher' })
    if (response.code === 0) {
      teachers.value = response.data.users
    }
  } catch (error) {
    console.error('获取教师列表失败:', error)
  }
}

// 获取课程列表
const fetchCourses = async () => {
  try {
    loading.value = true
    const params = { ...pagination, ...searchForm }
    
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getAllCourses(params)
    if (response.code === 0) {
      courses.value = response.data.courses
      total.value = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取课程列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchCourses()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.page = 1
  fetchCourses()
}

const handleAdd = () => {
  editDialog.mode = 'add'
  editDialog.title = '添加课程'
  editDialog.form = {
    code: '',
    name: '',
    credit: 2,
    capacity: 50,
    teacher_id: '',
    description: ''
  }
  editDialog.visible = true
}

const handleEdit = (course) => {
  editDialog.mode = 'edit'
  editDialog.title = '编辑课程'
  editDialog.form = { ...course }
  editDialog.visible = true
}

const handleSubmit = () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      editDialog.loading = true
      try {
        if (editDialog.mode === 'add') {
          const response = await createCourse(editDialog.form)
          if (response.code === 0) {
            ElMessage.success('课程创建成功！')
            editDialog.visible = false
            fetchCourses()
          }
        } else {
          const response = await updateCourse(editDialog.form.id, editDialog.form)
          if (response.code === 0) {
            ElMessage.success('课程更新成功！')
            editDialog.visible = false
            fetchCourses()
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
      } finally {
        editDialog.loading = false
      }
    }
  })
}

const handleDelete = async (course) => {
  try {
    await ElMessageBox.confirm(`确定要删除课程 "${course.name}" 吗？`, '删除课程', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deleteCourse(course.id)
    if (response.code === 0) {
      ElMessage.success('课程删除成功！')
      fetchCourses()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程失败:', error)
    }
  }
}

const handleViewStudents = async (course) => {
  studentDialog.title = `${course.name} - 学生列表`
  studentDialog.visible = true
  studentDialog.loading = true

  try {
    const response = await getCourseSelections({ courseId: course.id })
    if (response.code === 0) {
      studentDialog.students = response.data.selections
    }
  } catch (error) {
    ElMessage.error('获取学生列表失败')
  } finally {
    studentDialog.loading = false
  }
}

const handleSizeChange = () => {
  pagination.page = 1
  fetchCourses()
}

const handleCurrentChange = () => {
  fetchCourses()
}

onMounted(() => {
  fetchTeachers()
  fetchCourses()
})
</script>

<style scoped>
.course-management {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #909399;
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.enrollment-info {
  font-size: 12px;
  color: #606266;
}

.no-grade {
  color: #c0c4cc;
  font-size: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-table) {
  font-size: 14px;
}
</style> 